package com.xli.dto.component.model;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.xli.dto.component.model.query.Query;
import com.xli.dto.component.serializer.ModelSerializer;
import com.xli.dto.search.SearchDTO;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;


@Slf4j
@JsonSerialize(using = ModelSerializer.class)
public abstract class TableModel<V, E, D extends SearchDTO> extends Query<E, D> {

    private final List<V> data;

    private final D dto;

    @Setter
    private long total;

    public TableModel(D dto) {
        this.dto = dto;
        this.total = 0L;

        this.data = this.fetch(dto.getCurrent(), dto.getPageSize());
    }

    public abstract List<V> fetch(int current, int pageSize);

    public QueryWrapper<E> getQueryWrapper() {
        return this.buildQueryWrapper(dto);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{").append("\"total\":").append(total).append(",")
                .append("\"list\":").append("[");
        for (int i = 0; i < this.data.size(); i++) {
            V v = this.data.get(i);
            sb.append(JSONUtil.toJsonStr(v));
            if (i < data.size() - 1) {
                sb.append(",");
            }
        }
        sb.append("]}");
        return sb.toString();
    }
}
